package com.navinfo.parkingnavi.fragment;

import android.content.Context;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.JsonElement;
import com.mapbox.geojson.Feature;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.navinfo.parkingnavi.Adapter.SelectMapPoiAdapter;
import com.navinfo.parkingnavi.R;
import com.navinfo.parkingnavi.system.UrlManager;
import com.navinfo.parkingnavi.util.GsonManager;
import com.navinf.parkingnavi.util.MapManager;
import com.navinfo.parkingnavi.util.NetManager;
import com.navinfo.parkingnavi.util.mode.Poi;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/*
 *com.navinfo.parkingnavi.fragment
 *zhjch
 *2020/5/18
 *10:47
 *说明（poi抽屉列表）
 */
public class SelectMapPoiFragment extends BaseFragment implements MapboxMap.OnCameraMoveListener {

    private RecyclerView mListView;
    /**
     * poi列表适配器
     */
    private SelectMapPoiAdapter mAdapter;


    private Handler mHandler = new Handler(Looper.getMainLooper());

    private MapboxMap mapboxMap;
    private Call mCall;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mapboxMap = MapManager.getInstance().getMapBox();
        mapboxMap.addOnCameraMoveListener(this);
    }

    /*
     * 让activity监听
     */
    public interface OnSelectMapPoiFragmentListener extends OnBaseFragmentListener {

        void onSelectPoi(Poi poi);

    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mFragmentView = inflater.inflate(R.layout.fragment_select_map, null);
        mListView = mFragmentView.findViewById(R.id.select_map_poi_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mListView.setLayoutManager(layoutManager);
        mAdapter = new SelectMapPoiAdapter();
        mAdapter.addOnItemClickListener(new SelectMapPoiAdapter.OnItemClickListener() {
            @Override
            public void onShowPoi(Poi poi) {
                if (poi != null && mListener != null && mListener instanceof OnSelectMapPoiFragmentListener) {
                    ((OnSelectMapPoiFragmentListener) mListener).onSelectPoi(poi);
                }
            }

        });
        mFragmentView.findViewById(R.id.select_map_poi_loc).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MapManager.getInstance().jumpCurrentLoc();
            }
        });
        mListView.setAdapter(mAdapter);
        return mFragmentView;
    }

    @Override
    public void onDataChange(Bundle bundle) {
    }

    @Override
    public void onHideOrRemove(boolean bRemove) {
        super.onHideOrRemove(bRemove);
        if (bRemove) {
            mapboxMap.removeOnCameraMoveListener(this);
        }
        if (mCall != null && mCall.isExecuted()) {
            mCall.cancel();
            mCall = null;
        }
    }

    @Override
    public void onCameraMove() {
        mHandler.removeCallbacks(mapMoveRunnable);
        mHandler.postDelayed(mapMoveRunnable, 200);
    }

    private Runnable mapMoveRunnable = new Runnable() {
        @Override
        public void run() {
            if (mCall != null && mCall.isExecuted())
                mCall.cancel();
            String url = UrlManager.getRGeoCodeUrl(mapboxMap.getCameraPosition().target.getLatitude(), mapboxMap.getCameraPosition().target.getLongitude());
            mCall = NetManager.getInstance().getData(url, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    mCall = null;
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    mCall = null;
                    Poi poi = GsonManager.getInstance().parseGeoCodePoi(response.body().string());
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            String flrId = null;
                            String parkingId = null;
                            String name = null;

                            PointF pixel = MapManager.getInstance().getMapBox().getProjection().toScreenLocation(mapboxMap.getCameraPosition().target);
                            List<Feature> features = MapManager.getInstance().getMapBox().queryRenderedFeatures(pixel);
                            flrId = null;
                            parkingId = null;
                            name = null;
                            for (int i = 0; i < features.size(); i++) {
                                if (parkingId != null && name != null && flrId != null) {
                                    break;
                                }
                                Feature feature = features.get(i);
                                if (feature.properties() != null) {
                                    for (Map.Entry<String, JsonElement> entry : feature.properties().entrySet()) {
                                        Log.e("jingo", entry.getKey() + " " + entry.getValue());
                                        if (entry.getKey().equals("flr_id")) {
                                            flrId = entry.getValue().toString();
                                            if (flrId.startsWith("\"")) {
                                                flrId = flrId.substring(1);
                                            }
                                            if (flrId.endsWith("\"")) {
                                                flrId = flrId.substring(0, flrId.length() - 1);
                                            }
                                        }
                                        if (entry.getKey().equals("parking_id")) {
                                            parkingId = entry.getValue().toString();
                                            if (parkingId.startsWith("\"")) {
                                                parkingId = parkingId.substring(1);
                                            }
                                            if (parkingId.endsWith("\"")) {
                                                parkingId = parkingId.substring(0, parkingId.length() - 1);
                                            }
                                        }
                                        if (entry.getKey().equals("name")) {
                                            name = entry.getValue().toString();
                                            if (name.startsWith("\"")) {
                                                name = name.substring(1);
                                            }
                                            if (name.endsWith("\"")) {
                                                name = name.substring(0, name.length() - 1);
                                            }
                                        }
                                        if (parkingId != null && name != null && flrId != null) {
                                            break;
                                        }
                                    }
                                }
                            }


                            mListView.setVisibility(View.VISIBLE);
                            ArrayList<Poi> list = new ArrayList<>();


                            if(parkingId != null && flrId != null && name != null){
                                Poi newPoi = new Poi();
                                newPoi.setParkingId(parkingId);
                                newPoi.setFlrId(flrId);
                                newPoi.setName_zh(name);
                                newPoi.setLon(poi.getLon());
                                newPoi.setLat(poi.getLat());
                                newPoi.setAdmin_name(poi.getAdmin_name());
                                newPoi.setCity_name(poi.getCity_name());
                                newPoi.setCityadcode(poi.getCityadcode());
                                newPoi.setProvince_name(poi.getProvince_name());
                                newPoi.setKindcode(poi.getKindcode());
                                newPoi.setAdmincode(poi.getAdmincode());
                                list.add(newPoi);
                            }
                            list.add(poi);
                            mAdapter.setData(list);
                        }
                    });

                }
            });
        }
    };
}
